package com.example.controller.user;

import cn.hutool.crypto.SecureUtil;
import com.example.common.Constants;
import com.example.common.Result;
import com.example.entry.Rider;
import com.example.entry.User;
import com.example.exception.ServiceException;
import com.example.service.IRiderService;
import com.example.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

/*
* 用户前台控制器
* */
@RestController
@RequestMapping("/web/user")
public class UserWebController {

    @Resource
    private IUserService userService;

    @Resource
    IRiderService riderService;


    /*
    * 用户登录
    * */
    @PostMapping("/login")
    public Result userWebLogin(@RequestBody User user){

        if(user.getUsername().isEmpty() || user.getPassword().isEmpty()){
            return Result.error(Constants.CODE_500, "请输入用户名和密码");
        }
        User useredLogin = userService.userWebLogin(user);
        return Result.success(Constants.CODE_200, useredLogin);
    }

    /*
    *   骑手注册
    * */
    @PostMapping("/register-rider")
    public Result registerRider(@RequestBody Rider rider){
        System.out.println(rider.toString());
        User user = userService.getById(rider.getUserId());
        try {
            // 改变用户状态

            user.setIsRider(1);
            userService.updateById(user);

            // 保存骑手信息
            riderService.save(rider);
            return Result.success("注册成功");
        } catch (Exception e){
            throw new ServiceException(Constants.CODE_500, "注册失败");
        }
    }

    /*
    * 用户注册
    * */
    @PostMapping("/register")
    public Result userWebRegister(@RequestBody User user){
        if(user.getUsername().isEmpty() || user.getPassword().isEmpty()){
            return Result.error(Constants.CODE_500, "请输入用户名和密码");
        }
        Integer userWebRegister = userService.userWebRegister(user);
        return Result.success("注册成功",userWebRegister);
    }

    /*
    * 根据id查询用户
    * */
    @GetMapping("/find/id={id}")
    public Result findUserById(@PathVariable Integer id){
        User user = userService.getById(id);
        return Result.success("请求成功", user);
    }

    /*
    * 用户修改信息
    * */
    @PostMapping("/update")
    public Result updateUserInfo(@RequestBody User user){
        userService.updateById(user);
        return Result.success("修改成功");
    }

    /*
     * 用户修改密码
     * */
    @PostMapping("/update/password")
    public Result updateUserPassword(@RequestBody User user){
        user.setPassword(SecureUtil.md5(user.getPassword()));
        userService.updateById(user);
        return Result.success("修改成功");
    }
}
